//
//  HWDForgetViewController.m
//  Demo
//
//  Created by 龚碧容 on 2017/9/18.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "QLMForgetViewController.h"

@interface QLMForgetViewController ()<UITextFieldDelegate,UIAlertViewDelegate>

@property (nonatomic,strong) UITextField *oldpassportTextField;
@property (nonatomic,strong) UITextField *newpassportTextField;
@property (nonatomic,strong) UIButton *comfireButton;
@property (nonatomic,strong) UIView *line1View;
@property (nonatomic,strong) UIView *backtextfView;
@end

@implementation QLMForgetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title=@"密码修改";
    
    self.view.backgroundColor=UIColorFromRGB(0xf5f5f5);
    
    [self.view addSubview:self.backtextfView];
    [self.view addSubview:self.oldpassportTextField];
    
    if (_isBindBool) {
        self.title=@"绑定邀请码";
        
        if ([ClientTool isNull:self.invitationCodeStr]&&self.invitationCodeStr.length!=0) {
            self.oldpassportTextField.text=self.invitationCodeStr;
            self.oldpassportTextField.enabled=NO;
            self.comfireButton.enabled=NO;
            [_comfireButton setTitle:@"邀请码已绑定" forState:UIControlStateNormal];
        }else{
            self.oldpassportTextField.enabled=YES;
            self.comfireButton.enabled=YES;
        }
        
    }else{
        [self.view addSubview:self.newpassportTextField];
    }
    [self.view addSubview:self.line1View];
    [self.view addSubview:self.comfireButton];
    
    [self.view setNeedsUpdateConstraints];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=NO;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [_oldpassportTextField resignFirstResponder];
    [_newpassportTextField resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - update UI
- (void)updateViewConstraints{
    
    CGFloat heightEx=40;//高度
//    CGFloat topOri=10;//上边距
    CGFloat originX=20;//左右边距
    
    //新密码输入框
    [_backtextfView autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:0];
    [_backtextfView autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:0];//距离
    [_backtextfView autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:0];
    
    if (_isBindBool) {
        [_backtextfView autoSetDimension:ALDimensionHeight toSize:40];
    }else{
        [_backtextfView autoPinEdge:ALEdgeBottom toEdge:ALEdgeBottom ofView:_newpassportTextField withOffset:0];
    }
    
    //原密码输入框
    [_oldpassportTextField autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:0];
    [_oldpassportTextField autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:originX];
    [_oldpassportTextField autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:originX];
    [_oldpassportTextField autoSetDimension:ALDimensionHeight toSize:heightEx];
    
    [_line1View autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:_oldpassportTextField withOffset:0];
    [_line1View autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:originX];//距离
    [_line1View autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:originX];
    [_line1View autoSetDimension:ALDimensionHeight toSize:0.5];
    
    if (!_isBindBool) {
    //新密码输入框
        [_newpassportTextField autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:_oldpassportTextField withOffset:0.5];
        [_newpassportTextField autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:originX];//距离
        [_newpassportTextField autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:originX];
        [_newpassportTextField autoSetDimension:ALDimensionHeight toSize:heightEx];
    }
    
    [_comfireButton autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:IOS11_OR_LATER_SPACE(34)];//距离
    [_comfireButton autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:0];
    [_comfireButton autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:0];
    [_comfireButton autoSetDimension:ALDimensionHeight toSize:40];
    
    [super updateViewConstraints];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex==1) {
        
        NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
        NSDictionary *tokenDic=[NSDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];
        if ([token length]==0) {
            return;
        }
        
        NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        [dic setObject:_oldpassportTextField.text forKey:@"newCode"];

        [self.view makeToastActivity:CSToastPositionCenter];
        [ClientTool postUrlPath:@"/rest/changeInvitationCode" withParamers:dic andBody:tokenDic
                        success:^(id responseObject){
                            [self.view hideToastActivity];
                            NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                            if (code == 1) {
                                [self.navigationController popViewControllerAnimated:YES];
                            }else{
                                ETToast(responseObject[@"msg"]);
                            }
                        }failure:^(NSError *error){
                            [self.view hideToastActivity];
                            ETToast(@"服务器连接失败");
                        }
         ];
    }
}

#pragma mark - Action
- (void)comfireButtonAction:(UIButton *)sender{
    
    NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
    NSDictionary *tokenDic=[NSDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];
    if ([token length]==0) {
        return;
    }
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSString *urlPathStr=nil;
    if (!_isBindBool) {
    
        if (![ClientTool judgePassWordLegal:_oldpassportTextField.text]) {
            ETToast(@"请输入至少6位字母和数字组合的密码");
            return;
        }
        
        if (![ClientTool judgePassWordLegal:_newpassportTextField.text]) {
            ETToast(@"请输入至少6位字母和数字组合的密码");
            return;
        }
        
        [dic setObject:[ClientTool md5:_oldpassportTextField.text] forKey:@"oldPassword"];
        [dic setObject:[ClientTool md5:_newpassportTextField.text] forKey:@"newPassword"];
        
        urlPathStr=@"/user/modifyPassword";
    }else{
        
        if (![ClientTool isNull:_oldpassportTextField.text]||_oldpassportTextField.text.length==0) {
            ETToast(@"请输入邀请码");
            return;
        }
        
        if (![ClientTool isMobileValid:_oldpassportTextField.text]) {
            
            UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"提示" message:@"您输入的邀请码不是手机号码，是否继续提交？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alertView show];
            
            return;
        }
        
        [dic setObject:_oldpassportTextField.text forKey:@"newCode"];
        urlPathStr=@"/rest/changeInvitationCode";
    }
    
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:urlPathStr withParamers:dic andBody:tokenDic
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            
                            if (!_isBindBool) {
                                ETToastWithDelay(@"恭喜您，修改成功！", 1);
                                [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(delayShowHud) userInfo:nil repeats:NO];
                            }else{
                                [self.navigationController popViewControllerAnimated:YES];
                            }
                            
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}

- (void)delayShowHud{
    
    [[UserManager sharedManager] loginOut];
    [self.navigationController popToRootViewControllerAnimated:YES];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"pushTologinAction" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"loginUpdateMainUI" object:nil userInfo:nil];
}

#pragma mark - UITextField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - creatUI
- (UITextField *)oldpassportTextField{
    
    if (!_oldpassportTextField) {
        _oldpassportTextField=[UITextField newAutoLayoutView];
        
        if (!_isBindBool) {
            _oldpassportTextField.placeholder=@"请输入原密码";
            _oldpassportTextField.secureTextEntry=YES;
            _oldpassportTextField.keyboardType=UIKeyboardTypeEmailAddress;
        }else{
            _oldpassportTextField.placeholder=@"请输入邀请码";
            _oldpassportTextField.keyboardType=UIKeyboardTypeEmailAddress;
        }
        
        _oldpassportTextField.delegate=self;
        _oldpassportTextField.font=[UIFont systemFontOfSize:16];
        _oldpassportTextField.backgroundColor=[UIColor whiteColor];
        
        _oldpassportTextField.clearButtonMode=UITextFieldViewModeWhileEditing;
        
    }
    return _oldpassportTextField;
}

- (UITextField *)newpassportTextField{
    
    if (!_newpassportTextField) {
        _newpassportTextField=[UITextField newAutoLayoutView];
        _newpassportTextField.placeholder=@"请输入至少6位字母和数字组合的密码";
        _newpassportTextField.delegate=self;
        _newpassportTextField.font=[UIFont systemFontOfSize:16];
        _newpassportTextField.backgroundColor=[UIColor whiteColor];
        _newpassportTextField.keyboardType=UIKeyboardTypeEmailAddress;
        _newpassportTextField.clearButtonMode=UITextFieldViewModeWhileEditing;
        _newpassportTextField.secureTextEntry=YES;
    }
    return _newpassportTextField;
}

- (UIButton *)comfireButton{
    
    if (!_comfireButton) {
        _comfireButton=[UIButton buttonWithType:UIButtonTypeCustom];
        [_comfireButton setTitle:@"确认" forState:UIControlStateNormal];
        _comfireButton.backgroundColor=kButtonColor;
        _comfireButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;
        [_comfireButton setTitleColor:UIColorFromRGB(0xffffff) forState:UIControlStateNormal];
        _comfireButton.titleLabel.font=[UIFont boldSystemFontOfSize:18];
        [_comfireButton addTarget:self action:@selector(comfireButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _comfireButton;
}

- (UIView *)line1View{
    if (!_line1View) {
        _line1View=[UIView newAutoLayoutView];
        _line1View.backgroundColor=UIColorFromRGB(0xececec);
    }
    return _line1View;
}

- (UIView *)backtextfView{
    if (!_backtextfView) {
        _backtextfView=[UIView newAutoLayoutView];
        _backtextfView.backgroundColor=[UIColor whiteColor];
    }
    return _backtextfView;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
